package com.taichuan.selfcheck.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.taichuan.keysupport.Key;
import com.taichuan.keysupport.view.KSSpinner;
import com.taichuan.keysupport.view.panel.T12KSPanelEditText;
import com.taichuan.selfcheck.R;
import com.taichuan.selfcheck.mvp.presenter.AdbControlPresenter;
import com.taichuan.selfcheck.mvp.viewinterface.AdbControlInterface;
import com.taichuan.selfcheck.ui.activity.base.AppBaseActivity;
import com.taichuan.selfcheck.ui.fragment.base.AppBaseFragment;
import com.taichuan.tcutils.taichuan.SystemUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 该类主要用于
 *
 * @author CamelLuo
 * @version 2020/1/7
 */
public class AdbControlFragment extends AppBaseFragment<AdbControlInterface, AdbControlPresenter> implements AdbControlInterface {

    private final String TAG = AdbControlFragment.class.getSimpleName();

    @BindView(R.id.fragment_adb_control_adb_type_spinner)
    KSSpinner adbTypeSp;
    @BindView(R.id.fragment_adb_control_adb_editText)
    T12KSPanelEditText adbEt;
    @BindView(R.id.fragment_adb_control_check_button)
    Button checkBtn;
    @BindView(R.id.fragment_adb_control_result_textView)
    TextView resultTv;
    @BindView(R.id.tips_textView)
    TextView tipsTv;
    @BindView(R.id.selfAdbScroll)
    ScrollView selfAdbScroll;

    private String[] adbCommandValueArrary;
    private String[] adbCommandNameArrary;

    private final static int SCROLL_HEAD = 1;
    private final static int SCROLL_BOTTOM = 2;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case SCROLL_HEAD:
                    selfAdbScroll.fullScroll(ScrollView.FOCUS_UP);
                    break;
                case SCROLL_BOTTOM:
                    selfAdbScroll.fullScroll(ScrollView.FOCUS_DOWN);
                    break;
            }
            return false;
        }
    });

    @Override
    protected boolean isAllowAutoFinishFragment() {
        return false;
    }

    @Override
    public void doOnAutoFinishFragment() {
        if (!((AppBaseActivity)mActivity).getIsTouchDevice()) {       // 按键设备
            // TODO 按键设备，在编辑框和下拉框取得焦点时 ，禁止返回操作
            if (!adbEt.isFocused() && !adbTypeSp.isFocused()) {
                operateFragmentManagerBack();
            }
        }else {                     // 触屏设备
            operateFragmentManagerBack();
        }
    }

    @Override
    protected void getBundleValues(Bundle bundle) {

    }

    @Override
    protected int setContentViewId() {
        return R.layout.fragment_adb_control;
    }

    @Override
    protected void initView(View view, Bundle bundle) {
        tipsTv.setText(Html.fromHtml(getString(R.string.ctrl_tips_function)));
        adbEt.init(getContext(),((AppBaseActivity)mActivity).getIsTouchDevice());
        resultTv.setMovementMethod(ScrollingMovementMethod.getInstance());
        initSpnner();
        if(!SystemUtils.isTouchDevice()){
            initFocus();
        }
    }

    /**
     * 定义一个方法用于初始化 常用url地址选择Spinner
     */
    private void initSpnner() {
        //获取下拉列表显示内容的结果值数组
        adbCommandValueArrary = mActivity.getResources().getStringArray(R.array.adb_command_type_value);
        adbCommandNameArrary = mActivity.getResources().getStringArray(R.array.adb_command_type_name);

        adbTypeSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (adbCommandValueArrary != null && adbCommandValueArrary.length > 0 && position <= adbCommandValueArrary.length) {
                    if (adbCommandNameArrary != null && adbCommandNameArrary.length > 0 && position <= adbCommandNameArrary.length) {
                        showMsg("选中了 " + adbCommandNameArrary[position] + " 请按(#/OK/✔)键确认选择");
                    }

                    //获取点击的内容
                    String urlTypeValue = adbCommandValueArrary[position];
                    adbEt.setText(urlTypeValue);
                    //设置文本后要将光标移至末尾
                    if (!TextUtils.isEmpty(adbEt.getText().toString())){
                        Log.i(TAG, "initView: 将光标移至末尾");
                        adbEt.setSelection(adbEt.length());
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void initFocus() {
        mViewFocus.removeAll();
        mViewFocus.add(adbTypeSp);
        mViewFocus.add(adbEt);
        mViewFocus.add(checkBtn);
        mViewFocus.requestFocus(adbEt);
    }

    @OnClick(R.id.fragment_adb_control_check_button)
    @Override
    protected void onXmlClick(View v) {
        super.onXmlClick(v);
        switch (v.getId()){
            case R.id.fragment_adb_control_check_button:{
                //关闭软键盘
                hiddenSoftKeyboard();
                mPresenter.performAdbCommand(mActivity,adbEt.getText().toString().trim());
                break;
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (mViewFocus.onFocused(adbEt) ||
                mViewFocus.onFocused(adbTypeSp)) {           //当焦点在EditText,Spinner 等控件时
            if (event.getKeyCode() == Key.Convert.KEYCODE_LONG_XING){
                mViewFocus.nextFocus();
            }else {
                mViewFocus.handleClick();
            }
            //直接返回false让焦点控件消费掉按键事件，不再通知上级控件消费处理
            return false;
        }else {                                             //当不处于特殊焦点控件时
            switch (event.getKeyCode()){
                case Key.Convert.KEYCODE_1:
                    checkBtn.performClick();
                    break;
                case Key.Convert.KEYCODE_2:
                    mHandler.sendEmptyMessage(SCROLL_HEAD);
                    break;
                case Key.Convert.KEYCODE_8:
                    mHandler.sendEmptyMessage(SCROLL_BOTTOM);
                    break;
                case Key.Convert.KEYCODE_LONG_XING:
                    mViewFocus.nextFocus();
                    break;
                case Key.Convert.KEYCODE_JING:
                    mViewFocus.handleClick();
                    break;
                case Key.Convert.KEYCODE_XING:{
                    Log.i(TAG, "dispatchKeyEvent: 点击了返回键，退出页面");
                    appBaseActivity.clickBackKey();
                    //该Fragment的返回键事件交由其自身处理，不再通知上级控件消费处理
                    return true;
                }
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected AdbControlPresenter createPresenter() {
        return new AdbControlPresenter();
    }

    @Override
    public void showAdbPerformResult(String result) {
        resultTv.setText(result);
    }
}
